package com.zhentao.filter;

import cn.hutool.json.JSONUtil;
import com.zhentao.utils.JwtService;
import com.zhentao.utils.dtos.ResponseResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.zhentao.utils.enums.AppHttpCodeEnum.CHARGE_USER_TOKEN_EXCEPTION;

/**
 * @ClassName: AppGatewayFilter
 * @Author: 振涛教育_Q
 * @Date: 2024/10/23 16:25
 */
@Component
public class ChargeAdminGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 登录放行
        String url = request.getPath().toString();
        if(url.contains("/login") || url.contains("/logout") || url.contains("/uploadImg")){
            return chain.filter(exchange);
        }

        // token验证
        Map<String,Object> claimsBody = new HashMap<>();
        int i = 0;
        try {
            String token = request.getHeaders().getFirst("Authorization");

            if (!StringUtils.isEmpty(token)) {
                claimsBody = JwtService.getClaimsMap(token);
                i = JwtService.verifyToken(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // token 登录过期
        if(i == -2 || i == -3 || i == -1){
            byte[] bytes = JSONUtil.toJsonStr(ResponseResult.errorResult(CHARGE_USER_TOKEN_EXCEPTION)).getBytes(StandardCharsets.UTF_8);
            return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));
        }
        // token 有效
        if(i == 1){
            Object userId = claimsBody.get("id");
            // 将userId存储在Hearder 用于后面的拦截器使用
            request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
